package afk.biglog;

import java.io.*;

public class BlockReader
{

	private final RandomAccessFile raf;
	private final String charSet;

	public BlockReader(final File file, final String charset) throws FileNotFoundException
	{
		this.raf = new RandomAccessFile(file, "r");
		this.charSet = charset;
	}

	private String readLines(final int size, final BlockFilter filter) throws IOException
	{
		final byte[] buffer = new byte[size];
		if (raf.read(buffer) < size)
			throw new IOException("Truncated file");
		final BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer), charSet));

		final StringBuffer result = new StringBuffer();
		for (;;)
		{
			final String nextLine = reader.readLine();
			if (nextLine == null)
				break;
			if (filter.allow(nextLine))
				result.append(nextLine).append("\r\n");
		}

		return result.toString();
	}

	public void close() throws IOException
	{
		raf.close();
	}

	public String read(final Block block, final BlockFilter filter) throws IOException
	{
		synchronized (raf)
		{
			raf.seek(block.getStart());
			return readLines((int) (block.getEnd() - block.getStart()), filter);
		}
	}

}
